import { Toast } from "vant";
import {
  addFriendApply,
  getUserIdByQq,
  getGroupIdByNumber,
} from "@/request/add-request";

export const useAddFriendAplly = async (show,myId,friend_qq,fromName,fromAvatar,qq_account, t) => {
  const type = t;
  let uId = null;
  try {
    if (qq_account === friend_qq.value && type === "private") {
      return Toast("不能添加自己");
    }
    if (friend_qq.value.length <= 0) {
      return Toast("不能为空");
    }
    if (type === "private") {
      uId = await useGetUserIdByQq(friend_qq.value);
    } else {
      // 这里的 friend_qq 是群号
      uId = await getGroupIdByNumber(friend_qq.value);
    }
    if (!uId.data) {
      return Toast("群不存在");
    }
    const toId = uId.data?.group_creator ? uId.data?.group_creator : uId.data._id;
    if (uId.code === 201 && uId.message === "success" && uId.data) {
      if (myId === toId) {
        return Toast("不能加入自己创建的群");
      }
      show.value = true;
      const result = await addFriendApply( myId, toId, type, fromName, fromAvatar ,uId.data._id);
      if (result.code === 201 && result.message === "success") {
        Toast("添加申请已发送");
        friend_qq.value = "";
      } else {
        Toast(result.message);
      }
      show.value = false;
    } else {
      Toast(uId.message);
    }
  } catch (error) {
    Toast(error.message);
  }
};

export const useGetUserIdByQq = async (qq_account) => {
  return await getUserIdByQq(qq_account);
};
